package com.mkx.domain.vo;

import lombok.Getter;

import java.util.regex.Pattern;

/**
 * 邮箱值对象
 * 封装邮箱地址的验证和处理逻辑
 */
@Getter
public class Email {
    
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
    
    private final String address;
    
    /**
     * 构造函数
     * @param address 邮箱地址
     * @throws IllegalArgumentException 当邮箱地址无效时抛出
     */
    public Email(String address) {
        if (address == null || address.trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱地址不能为空");
        }
        if (!isValid(address)) {
            throw new IllegalArgumentException("无效的邮箱地址格式");
        }
        this.address = address.trim().toLowerCase();
    }
    
    /**
     * 验证邮箱地址格式
     */
    private boolean isValid(String email) {
        return EMAIL_PATTERN.matcher(email).matches();
    }
    
    /**
     * 获取邮箱的域名部分
     */
    public String getDomain() {
        int atIndex = address.indexOf('@');
        if (atIndex > 0) {
            return address.substring(atIndex + 1);
        }
        return "";
    }
    
    /**
     * 获取邮箱的用户名部分
     */
    public String getUsername() {
        int atIndex = address.indexOf('@');
        if (atIndex > 0) {
            return address.substring(0, atIndex);
        }
        return address;
    }
    
    @Override
    public String toString() {
        return address;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Email email = (Email) obj;
        return address.equals(email.address);
    }
    
    @Override
    public int hashCode() {
        return address.hashCode();
    }
}